﻿using UnityEngine;
using System.Collections;

public class MBDButtonScript : MonoBehaviour {
	
	public int buttonOfDoorID;
	public MultiLockBWDoor myDoor;
	Renderer rendererObject;
	public Texture2D offTex;
	public Texture2D onTex;
	Transform colidedPlayer;
	bool isActivated = false;
	// Use this for initialization
	void Start () {
		//if(myDoor != null)
			//myDoor.addAButton(this);
		rendererObject = transform.GetChild(0).renderer;
	}
	// Update is called once per frame
	void Update () {
		if(colidedPlayer)
		{
			if(colidedPlayer.position.y < transform.position.y)
				networkView.RPC("activate",RPCMode.All,false);
		}
	}
	
	void OnTriggerStay(Collider myCol)
	{
		if(isActivated)
			return;
		
		if(myCol.tag == "Player")
		{
			if(myCol.transform.position.y > transform.position.y)
			{
				networkView.RPC("activate",RPCMode.All,true);
				colidedPlayer = myCol.transform;
			}
		}
		else if(myCol.tag == "Item")
		{
			networkView.RPC("activate",RPCMode.All,true);
		}
	}
	
	void OnTriggerExit(Collider myCol)
	{
		//if(partner.isMoving)
		if(isActivated)
			networkView.RPC("activate",RPCMode.All,false);
	}
	
	public void killFunctionality()
	{
		renderer.material.mainTexture = rendererObject.material.mainTexture = onTex;
		
		Destroy(this);
	}
	
	[RPC]
	void activate(bool isActive)
	{
		isActivated = isActive;
		myDoor.setButtonActive(buttonOfDoorID,isActive);
		if(isActive)
		{
			if(rendererObject.material.mainTexture != onTex)
			{
				rendererObject.material.mainTexture = onTex;
			}
		}
		else
		{
			if(rendererObject.material.mainTexture != offTex)
			{
				rendererObject.material.mainTexture = offTex;
			}
			colidedPlayer = null;
		}
	}
}
